define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {
	$("input[name='row[pay_type]']").on('change', function() {
		var val = $(this).val();
		if(val == 2){
			 $(".display_cost_id").slideDown();
		}else{
			 $(".display_cost_id").slideUp();
		}
	}); 
	$(document).on('keyup change focus blur', ".type2name", function () {
		var type2num = 0;
		$(".type2name").each(function () {
			if($(this).val()){
				type2num +=  parseFloat($(this).val());
			}
		});	
		if(type2num && type2num > 100){
			layer.msg('百分比不能超过100,请修改');
			$(this).val('');
		}
	});
	$(document).on('mousewheel', "input[type='number']", function () {
		 return false;
	});
    //监听文本框改变事件
	$(document).on('focus', ".fieldlist input", function () {
		var tmptxt = $(this).val();    
		var tepclass = $(this).attr("class");
		if(tepclass == 'form-control venue_salse desc') return false;
		var prcing_type = 0;
		var val = '';
		if(tepclass == 'form-control venue_salse  pricing_num'){
			var attrite = $(this).attr('attrite');  
			var arr = attrite.split("_");
			prcing_type = $(".pricing_type_"+arr[2]+"").val();
		}
		if(tmptxt == 0){
			$(this).val('');
		}else{
			$(this).val(tmptxt.replace(/[^\- \d.]/g,''));
			val = tmptxt.replace(/[^\- \d.]/g,'');
		}
		if(prcing_type == 1){
			$(".round_num_"+arr[2]+"").val(val);
		}
	});
    //监听文本框改变事件
	$(document).on('blur', ".fieldlist input", function () {
		var tmptxt = $(this).val();   
		var tepclass = $(this).attr("class");
		if(tepclass == 'form-control venue_salse desc') return false;
		var prcing_type = 0;
		var val = '';
		if(tepclass == 'form-control venue_salse  pricing_num'){
			var attrite = $(this).attr('attrite');  
			var arr = attrite.split("_");
			prcing_type = $(".pricing_type_"+arr[2]+"").val();
		}
		if(tmptxt == ''){
			$(this).val(0);
		}else{
			$(this).val(tmptxt.replace(/[^\- \d.]/g,''));
			val = tmptxt.replace(/[^\- \d.]/g,'');
		}
		if(prcing_type == 1){
			$(".round_num_"+arr[2]+"").val(val);
		}
	});
    //获取改变事件
	$(document).on('change', ".pricing_type", function () {
		var val = $(this).val();   
		var attrite = $(this).attr('attrite');   
		var arr = attrite.split("_");
		if(val == 1){
			$(".pricing_price1_"+arr[2]+"").removeClass("hide");
			$(".pricing_price2_"+arr[2]+"").addClass("hide");
		}else{
			$(".pricing_price1_"+arr[2]+"").addClass("hide");
			$(".pricing_price2_"+arr[2]+"").removeClass("hide");
		}
	});
 
	//展开隐藏
	$(document.body).on("click", ".btn-toggle", function (e) {
		$("a.btn-node-sub[data-id][data-pid][data-pid!=0].disabled").closest("tr").toggle();
		var that = this;
		var show = $("i", that).hasClass("fa-chevron-down");
		$("i", that).toggleClass("fa-chevron-down", !show);
		$("i", that).toggleClass("fa-chevron-up", show);
		$(".btn-node-sub[data-pid=0]").data("shown", show);
	});
	 //显示隐藏子节点
	$(".btn-node-sub").off("click").on("click", function (e) {
		$("a.btn-node-sub[data-pid='" + $(this).data("id") + "']").each(function () {
			$(this).closest("tr").toggle();
		});
		return false;
	});

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'finance/extract/week/index',
                    generate_url: 'finance/extract/week/generate',
                    excel_url: 'finance/extract/week/excel',
                    generate_tax_url: 'finance/extract/week/generate_tax',
                    generate_group_url: 'finance/extract/week/group',
                    add_url: 'finance/extract/week/add',
                    table: 'finance_extract_week',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'start_time',
				searchFormVisible: true,
                searchFormTemplate: 'customformtpl',
                columns: [
                    [
					     {field: '', title: __('序号'), formatter: function (value, row, index) {
                            var options = table.bootstrapTable('getOptions');
                            var pageNumber = options.pageNumber;
                            var pageSize = options.pageSize;

                            return (pageNumber - 1) * pageSize + 1 + index;
                        }, operate: false},
						{

                            field: 'name',
                            title: __('Name'),
							table: table,
                            events: Table.api.events.operate,
                            formatter: Controller.api.formatter.group,
                        },
						{field: 'start_time', title: __('Start_time')},
						{field: 'end_time', title: __('End_time')},
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
         group:function(){
            $("#append").click(function () {
                $("#fieldlist").find('.hidden').eq(0).removeClass('hidden');
            });
            $(".btn-removes").on('click',function () {
                var dd = $(this).parent('dd');
                var sid = dd.find('select').attr('id');
                $("#"+sid).selectpicker('val','');
                $("#"+sid).selectpicker('refresh');
                $(dd).addClass('hidden');
            })

            $('#sel1').on('changed.bs.select',function(e, clickedIndex, isSelected, previousValue){
               var cs = merge(1);
                if (isSelected==1){
                    var val = $("#sel1").find('option').eq(clickedIndex).val();
                    if(in_array(val,cs.arr)){
                       var s1 = removes(val,$("#sel1").selectpicker('val'));
                       $("#sel1").selectpicker('val',s1);
                       Layer.msg("已经选择");	
                    }

               }
            });

            $('#sel2').on('changed.bs.select',function(e, clickedIndex, isSelected, previousValue){
                var cs = merge(2);
                if (isSelected==1){
                    var val = $("#sel2").find('option').eq(clickedIndex).val();
                    if(in_array(val,cs.arr)){
                        var s1 = removes(val,$("#sel2").selectpicker('val'));
                        $("#sel2").selectpicker('val',s1);
                        Layer.msg("已经选择");	
                    }

                }
            });
            $('#sel3').on('changed.bs.select',function(e, clickedIndex, isSelected, previousValue){
                var cs = merge(3);
                if (isSelected==1){
                    var val = $("#sel3").find('option').eq(clickedIndex).val();
                    if(in_array(val,cs.arr)){
                        var s1 = removes(val,$("#sel3").selectpicker('val'));
                        $("#sel3").selectpicker('val',s1);
                        Layer.msg("已经选择");	
                    }

                }
            });
            $('#sel4').on('changed.bs.select',function(e, clickedIndex, isSelected, previousValue){
                var cs = merge(4);
                if (isSelected==1){
                    var val = $("#sel4").find('option').eq(clickedIndex).val();
                    if(in_array(val,cs.arr)){
                        var s1 = removes(val,$("#sel4").selectpicker('val'));
                        $("#sel4").selectpicker('val',s1);
                        Layer.msg("已经选择");	
                    }

                }
            });
            $('#sel5').on('changed.bs.select',function(e, clickedIndex, isSelected, previousValue){
                var cs = merge(5);
                if (isSelected==1){
                    var val = $("#sel5").find('option').eq(clickedIndex).val();
                    if(in_array(val,cs.arr)){
                        var s1 = removes(val,$("#sel5").selectpicker('val'));
                        $("#sel5").selectpicker('val',s1);
                        Layer.msg("已经选择");	
                    }

                }
            });
            $('#sel6').on('changed.bs.select',function(e, clickedIndex, isSelected, previousValue){
                var cs = merge(6);
                if (isSelected==1){
                    var val = $("#sel6").find('option').eq(clickedIndex).val();
                    if(in_array(val,cs.arr)){
                        var s1 = removes(val,$("#sel6").selectpicker('val'));
                        $("#sel6").selectpicker('val',s1);
                        Layer.msg("已经选择");	
                    }

                }
            });
            //数组合并，不合并指定的数组
            function merge(h){
                var arr=[];
                var obj;
               for (var i=1;i<=6;i++){
                   if($("#sel"+i).selectpicker('val')!=null && i!=h) {
                       for (var j = 0; j < $("#sel" + i).selectpicker('val').length; j++) {
                           arr.push($("#sel"+i).selectpicker('val')[j]);
                       }
                   }
                   if (h==i){
                       obj = $("#sel"+i).selectpicker('val');
                   }
               }
               return {arr:arr,obj:obj};
            }
            //php in-array
            function in_array(search,array){
                for(var i in array){
                    if(array[i]==search){
                        return true;
                    }
                }
                return false;
            }
            //删除数组中指定的元素
            function removes(val,arrs) {
                if (arrs === undefined || arrs.length == 0) return [];

                var arr=[];

                for (var i in arrs){
                    if (arrs[i]!=val) {
                        arr.push(arrs[i]);
                    }
                }
                return arr;
            }
            Controller.api.bindevent();



        },
        index2: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'finance/extract/week/index2',
                    status_url: 'finance/extract/week/status',
                    check_url: 'finance/extract/week/check',
                    generate_url: 'finance/extract/week/generate',
                    excel_url: 'finance/extract/week/excel',
                    generate_tax_url: 'finance/extract/week/generate_tax',
                    add_url: 'finance/extract/week/add',
                    edit_url: 'finance/extract/week/edit',
                    del_url: 'finance/extract/week/delete',
                    books_url: 'finance/extract/week/finance_books',
                    multi_url: 'finance/extract/week/multi',
                    table: 'finance_extract_week',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
				searchFormVisible: true,
				searchFormTemplate: 'customformtpl',
				//禁用默认搜索
                search: false,
                //启用普通表单搜索
                commonSearch: true,
                queryParams: function (params) {
                    //这里可以追加搜索条件
					var filter = params.filter ? JSON.parse(params.filter) : {}; //判断当前是否还有其他高级搜索栏的条件
                    var op = params.op ? JSON.parse(params.op) : {}; 
					//这里可以动态赋值，比如从URL中获取admin_id的值，filter.admin_id=Fast.api.query('admin_id');
                    filter.start_time = Fast.api.query('start_time');
                    op.start_time = "=";
                    filter.end_time = Fast.api.query('end_time');
                    op.end_time = "=";
					if(Fast.api.query('department')){
						filter.department = filter.department ? filter.department : Fast.api.query('department');
						op.department = "FIND_IN_SET";
					}
                    params.filter = JSON.stringify(filter);
                    params.op = JSON.stringify(op);
                    return params;
                },
                columns: [
                    [
                        {checkbox: true},
						//{field: 'id', title: __('Id')},
						{
                            field: 'name',
                            title: __('Name'),
							table: table,
                            events: Table.api.events.operate,
							buttons: [],
                            formatter: Controller.api.formatter.zdyname
                        },
                        
						{field: 'start_time', title: __('Start_time')},
                        
						{field: 'end_time', title: __('End_time')},
                        
						{field: 'division_method', title: __('Division_method'), searchList: {"1":__('Division_method 1'),"2":__('Division_method 2')}, formatter: Table.api.formatter.normal},
						{field: 'division_method_round', title: __('Division_method_round'), searchList: {"1":__('Division_method_round 1'),"2":__('Division_method_round 2')}, formatter: Table.api.formatter.normal},
                        
						{
							field: 'status', 
							title: __('Status'), 
							searchList: {"1":__('Status 1'),"2":__('Status 2'),"3":__('Status 3'),"4":__('Status 4')},
							events: Controller.api.events.statusName,
							formatter: Controller.api.formatter.statusName},
								 //Table.api.formatter.normal
   
						{field: 'department_text', title: __('Department')},
						//{field: 'createtime', title: __('Createtime'), formatter: Table.api.formatter.datetime},
                        
						//{field: 'updatetime', title: __('Updatetime'), formatter: Table.api.formatter.datetime},
                        
						{field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate,formatter: Controller.api.formatter.operate},
						//{field:"publish",title:"", defaultValue:'ceshi'}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },  
        view: function () {
            Controller.api.bindevent();
             $(document).on('click', ".pricing_data", function () {
               var id = $(this).attr("attrv");
               pricing_data(id);
            });
            function pricing_data(k){
                var data_info = $(".pricing_data_"+k).text();
                 var content_data ='<table class="table table-striped table-bordered table-hover table-nowrap" data-operate-edit="1" data-operate-del="1" width="100%"><thead><tr> <th>单科定价</th><th >单科数量</th><th >总价</th></tr></thead><tbody id="ultable" >';
                 content_data += data_info+'</tbody></table>';
                 layer.open({
                   type: 1,
                   skin: 'layui-layer-demo', //样式类名
                   title:'组合定价详情',
                   //closeBtn: 0, //不显示关闭按钮
                   anim: 2,
                   shadeClose: true, //开启遮罩关闭
                   
                   content: content_data
                });
            }
        },
        finance_books: function () {
            Controller.api.bindevent();
        },
        status: function () {
            Controller.api.bindevent();
        },
        public_add: function () {
            Controller.api.bindevent();
              setTimeout(function(){
                $("#c-week").selectpicker('refresh');
                console.log(1);
              },1000);
             $(document).on("change", "#c-week", function () {
                  setTimeout(function(){
                    $("#c-season").selectpicker("refresh");
                    console.log(2);
                  },1000); 
                  $("#week_id").val($(this).val());
              }); 
             $(document).on("change", "#c-season", function () {
                  setTimeout(function(){
                    $("#c-school").selectpicker("refresh");
                     console.log(3);
                  },1000); 
                  $("#season_id").val($(this).val());
              });  
             $(document).on("change", "#c-school", function () {
                  $("#school_id").val($(this).val());
              });
        },
        public_edit: function () {
            Controller.api.bindevent();
            $(document).on('change', ".pricing_type", function () {
               var pricing_type = $(this).val();
               var id = $(this).attr("attrv");
               if(pricing_type == 2){
               		$(".pricing_type_click_"+id).removeClass('hide');
               		
                	salesPricing(id);
                    return false;
                }else{
                	$(".pricing_type_click_"+id).addClass('hide');
                }
            });  
            $(document).on('click', ".pricing_type_click", function () {
               var id = $(this).attr("attrv");
               salesPricing(id);
            });
            function  salesPricing(id){
            	$("#defauftid").attr("value",id);
        		Fast.api.open('finance/extract/week/sales_pricing/id/'+id,'组合定价详情',{
                   area: ['50%', '70%'],
				   callback: function (data) {
					   	var id = data.id;
					   	$("#pricing_data_"+id).val(data.type).change();
					   	$("#pricing_data_"+id).attr("value",data.type);
					   
                   }
           		});
            }
        },
        sales_pricing: function () {
        	var id= $(".defauftid" , parent.document).val();
        	var pricing_data = $("#pricing_data_"+id , parent.document).val();
        	$(".pricing_data").text(pricing_data);
 			 Form.api.bindevent($("form[role=form]"), function (data) {
                Fast.api.close(data);
            });
        },
        generate: function () {
            Controller.api.bindevent();
            Controller.api.week();
        },
        excel: function () {
			 Form.api.bindevent($("form[role=form]"), function(data, ret){
				 if(data == 1){
					  console.log(ret.url);
					  setTimeout(function(){
						document.location.href = ret.url;
					  },50);
				}else{
					console.log(data.url);
					for (var i=0;i<data.length;i++){
						 console.log(data[i].url);
						 window.open(data[i].url,'_blank');
					}
					
				}
			}, function(data, ret){
				console.log('错误');
			});
		   $("select[name='type']").on('change', function() {
				var val = $(this).val();
				var DefaultsTime = $("#DefaultsTime").val();
				var fa = $(".btn-group.bootstrap-select.date.form-control");
				if(val == 2){
					$("#c-date").selectpicker('val',DefaultsTime);
					$("#c-date").removeAttr("multiple");
					fa.removeClass("show-tick");
				}else{
					$("#c-date").attr("multiple",'');
					fa.addClass("show-tick");
				}
				$("#c-date").selectpicker("refresh");
				$("#c-date").selectpicker();
			}); 
			Controller.api.week();
        },
        generate_tax: function () {
			 Form.api.bindevent($("form[role=form]"), function(data, ret){
				  setTimeout(function(){
					document.location.href = ret.url;
				  },50);
			}, function(data, ret){
				console.log('错误');
			});
			$(document).on('click', '.btn-success', function () {
				   $("#submitvalue").val($(this).val());
				  // $(".generate_tax").submit();
            });
			Controller.api.week();
        },
		detail: function () {
            $(document).on('click', '.btn-callback', function () {
                Fast.api.close($("input[name=callback]").val());
            });
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            week: function () {
				 setTimeout(function(){
					$("#c-year").selectpicker('refresh');
				  },800);
				  var DefaultsTime = $("#DefaultsTime").val();
				 $(document).on("change", "#c-year", function () {
					  setTimeout(function(){
						$("#c-date").selectpicker('val',DefaultsTime);
						$("#c-date").selectpicker("refresh");
						$("#c-date").selectpicker();
					  },800); 
                });
            },
			formatter: {//渲染的方法
                view: function (value, row, index) {
					var department =  $('#department option:selected').val();
					var department_w =  '';
					if(department) department_w = "&department="+department;
					  //这里手动构造URL
                    url = "finance/extract/week/index2?start_time=" + row.start_time+"&end_time="+row.end_time+department_w;
                    //url = "finance/extract/week/index2?name=dsadasd&end_time="+row.end_time;
                     //方式一,直接返回class带有addtabsit的链接,这可以方便自定义显示内容
                    return '<a href="' + url + '" class="addtabsit" title="' + __("Search %s", value) + '">' + __('Search %s', value) + '</a>';
                },
                zdyname: function (value, row, index) {
                    var table = this.table;
                    // 默认按钮组
                    var buttons = [];
					buttons.push({
								name: 'detail',
								title: row.name,
								text: row.name,
								extend: 'data-toggle="tooltip"',
								classname: 'btn btn-xs btn-dialog',
								url: 'finance/extract/week/view',
                                extend:'data-area=\'["80%","80%"]\'',
							});
					return Table.api.buttonlink(this, buttons, value, row, index, 'buttons');
                },
                statusName: function (value, row, index) {
				 if(row.status == 4 || row.status == 3){
					 return '<a class="btn btn-xs btn-dialog btn-ip"> '+row.status_text+ '</a>';
				 }else{
					 return row.status_text;
				 }
                },
              
                group: function (value, row, index) {
					var table = this.table;
                    // 操作配置
                    var options = table ? table.bootstrapTable('getOptions') : {};
                    // 默认按钮组
                    var buttons = $.extend([], this.buttons || []);
                    var department =  $('#department option:selected').val();
					var department_w =  '';
					if(department) department_w = "&department="+department;
					  //这里手动构造URL
                    url = "finance/extract/week/index2?start_time=" + row.start_time+"&end_time="+row.end_time+department_w;
                    url2 = "finance/extract/week/group?start_time=" + row.start_time+"&end_time="+row.end_time;
                    //url = "finance/extract/week/index2?name=dsadasd&end_time="+row.end_time;
                     //方式一,直接返回class带有addtabsit的链接,这可以方便自定义显示内容
                    return '<a href="' + url + '" class="addtabsit" title="' + __("Search %s", value) + '">' + __('Search %s', value) + '</a>'+'&nbsp;&nbsp;'+'<a href="' + url2 + '" class="btn btn-xs btn-primary btn-dialog" title="' + __("分组") + '"><i class="fa fa-list"></i>' + __("分组") + '</a>';
                },
                operate: function (value, row, index) {
					var table = this.table;
                    // 操作配置
                    var options = table ? table.bootstrapTable('getOptions') : {};
                    // 默认按钮组
                    var buttons = $.extend([], this.buttons || []);
					if (options.extend.books_url !== ''){
							buttons.push({
								name: 'books',
								icon: 'fa fa-tags',
								title: __('Books.type 2'),
								extend: 'data-toggle="tooltip"',
								classname: 'btn btn-xs btn-success btn-booksone',
								
								url: options.extend.books_url
							});
					 }

					if(row.status == 3 ){
                        if (options.extend.status_url !== '') {
                             buttons.push({
                                 name: 'status',
                                 icon: 'fa fa-sticky-note',
                                 title: __('SubStatus'),
                                 extend: 'data-toggle="tooltip"',
                                 classname: 'btn btn-xs btn-success btn-statusone',
                                 url: options.extend.status_url
                                    
                             });
                         }
						// if (options.extend.check_url !== ''){
						// 	buttons.push({
						// 		name: 'check',
						// 		icon: 'fa fa-paper-plane',
						// 		title: __('Check'),
						// 		extend: 'data-toggle="tooltip"',
						// 		classname: 'btn btn-xs btn-success btn-checkone',
						// 		url: options.extend.check_url
						// 	});
						// }
					// //fa fa-sticky-note
					// 	if (options.extend.edit_url !== ''){
					// 		buttons.push({
					// 			name: 'edit',
					// 			icon: 'fa fa-pencil',
					// 			title: __('Edit'),
					// 			extend: 'data-toggle="tooltip"',
					// 			classname: 'btn btn-xs btn-success btn-editone',
					// 			url: options.extend.edit_url
					// 		});
					// 	}
					// 	if (options.extend.del_url !== '') {
					// 		buttons.push({
					// 			name: 'del',
					// 			icon: 'fa fa-trash',
					// 			title: __('Del'),
					// 			extend: 'data-toggle="tooltip"',
					// 			classname: 'btn btn-xs btn-danger btn-delone',
					// 			url: options.extend.del_url
					// 		});
					// 	}
					// }else if(row.status == 2){
				
					}

					return Table.api.buttonlink(this, buttons, value, row, index, 'operate');
                },
          },
          events: {//绑定事件的方法

                statusName: {
                    //格式为：方法名+空格+DOM元素
                    'click .btn-ip': function (e, value, row, index) {
                        e.stopPropagation();
                        Layer.alert("审核信息: <code>" + row.status_desc + "</code>");
                    }
                }
            }
		
        }
    };
    return Controller;
});